﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace DDU.Converters
{
    public class BufferLengthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            culture = new CultureInfo("en-US");
            NumberFormatInfo format = culture.NumberFormat;
            format.NumberDecimalDigits = 2;
            Double length = System.Convert.ToDouble(value, culture.NumberFormat);

            string _unit = "Bytes";
            double _value = 0.00;

            if (length < 1024)
            {
                _value = length;
                _unit = "Bytes";
            }
            else if (length > 1024 && length < 1024 * 1024)
            {
                _value = System.Convert.ToDouble(length / 1024, format);
                _unit = "KB";
            }
            else if (length > 1024 * 1024 && length < 1024 * 1024 * 1024)
            {
                _value = System.Convert.ToDouble(length / (1024 * 1024), format);
                _unit = "MB";
            }
            else
            {
                _value = System.Convert.ToDouble(length / (1024 * 1024 * 1024), format);
                _unit = "GB";
            }

            return string.Format("{0} {1}", Math.Round(_value, 2), _unit);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
